# app/core/events.py

from fastapi import FastAPI
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text
from app.db.session import async_session
from app.db.redis import redis

async def check_postgres():
    async with async_session() as session:
        result = await session.execute(text("SELECT 1"))
        return result.scalar_one()

async def check_redis():
    await redis.set("health_check", "ok", ex=5)
    val = await redis.get("health_check")
    return val == "ok"

def register_events(app: FastAPI):
    @app.on_event("startup")
    async def startup_event():
        print("🚀 正在启动 AI Chat 后端服务...")
        try:
            db_ok = await check_postgres()
            redis_ok = await check_redis()
            if db_ok == 1 and redis_ok:
                print("✅ 数据库与 Redis 均连接成功！")
        except Exception as e:
            print(f"❌ 启动检测失败：{e}")

    @app.on_event("shutdown")
    async def shutdown_event():
        print("🛑 服务已关闭，释放连接资源...")
        await redis.close()
